

MsgPanel = function(configs) {
	this.lastMsgId;
	
	this.lineCount = 0;
	this.defaultStyle = {padding : '5px', fontSize : '12px'};
	this.oddStyle = {background : '#F1F1F1'};
	this.evenStyle = {background : '#fff'};

	MsgPanel.superclass.constructor.call(this, Ext.apply({
		autoScroll : true
	}, configs));
}
Ext.extend(MsgPanel, Ext.Panel, {
	updateContent : function(value) {
		var result = Ext.util.JSON.decode(value);
		var i = 0;
		for (;i < result.messages.length - 1; i++) {
			this.addMessage(result.messages[i]);
		}
		
		this.lastMsgId = result.messages[i].id;
		
		var lastMsgElem = this.addMessage(result.messages[i]);
		var top = lastMsgElem.getOffsetsTo(this.body)[1] + this.body.dom.scrollTop;

		this.body.scrollTo('top', top, {duration : .75});
	},
	
	addMessage : function(msg) {
		var style = Ext.apply({},
		((this.lineCount++) % 2 == 0 ? this.evenStyle : this.oddStyle), this.defaultStyle);

		return this.body.createChild({html : msg.user + ' : ' + msg.content, style : style});
	}
});

ChatWindow = function(configs) {
	this.msgPanel = new MsgPanel({region : 'center'});
	this.msgField = new Ext.form.TextField({
				id : 'msg',
				name : 'msg',
				width : '100%'
		});
	this.sendButton = new Ext.Button({
				text : 'send',
				handler : this.sendMsg,
				scope : this
		});
	this.user = configs.user;

	ChatWindow.superclass.constructor.call(this, {
		title : configs.title,
		width: 500,
	    height:300,
	    minWidth: 300,
	    minHeight: 200,
	    layout: 'border',
	    plain:true,
	    bodyStyle:'padding:5px;',

	    items: [this.msgPanel, {
			region : 'south',
			height : 25,
			layout : 'column',
			items : [{
				columnWidth : 1,
				items : this.msgField
			}, {
				items : this.sendButton
			}]
		}]
	});
};

Ext.extend(ChatWindow, Ext.Window, {
	sendMsg : function() {
		Ext.Ajax.request({
			url : 'send.groovy',
			success : function(resp) {
				this.msgPanel.updateContent(resp.responseText);
			},
			scope : this,
			params : {
				user : this.user,
				msg : this.msgField.getValue(),
				lastMsgId : this.msgPanel.lastMsgId
			}
		});
	}
});

UserPanel = function (configs) {
	this.user = configs.user;
	this.chatWindow;

	UserPanel.superclass.constructor.call(this, Ext.apply({
		plain : true,
		border : false,
		style : {fontSize : '12px', padding : '2px', cursor : 'pointer'},
		html : this.user
	}, configs));
}
Ext.extend(UserPanel, Ext.Panel, {
	onRender : function (ct, position) {
		UserPanel.superclass.onRender.apply(this, arguments);
		this.body.on('mouseover', function () {
			this.setStyle('background', '#f1f1f1');
		});
		this.body.on('mouseout', function () {
			this.setStyle('background', '#fff');
		});
		this.body.on('click', function () {
			this.openChatWindow();
		}, this);
	},

	openChatWindow : function () {
		if(!this.chatWindow) {
			this.chatWindow = new ChatWindow({user : CURRENT_USER, title : 'Chat with ' + this.user});
		}

		this.chatWindow.show();
	}
});

ListUsersPanel = function (configs) {
	var tree = new Ext.tree.TreePanel({
                        id:'im-tree',
                        title: 'Online Users',
                        loader: new Ext.tree.TreeLoader({
                        	dataUrl : 'listUsers.groovy'
                        }),
                        rootVisible:false,
                        lines:false,
                        autoScroll:true,
                        useArrows : true,
                        tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('im-tree');
                                    //tree.body.mask('Loading', 'x-mask-loading');
                                    tree.root.reload();
                                    tree.root.collapse(true, false);
                                    /*setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        tree.root.expand(true, true);
                                    }, 1000);*/
                                }
                            }
                        }],
                        root: new Ext.tree.AsyncTreeNode({
                            text:'Online'
                        })
                    });
	/*tree.root.startAutoRefresh = function(interval) {
		if(this.autoRefreshProcId){
        	clearInterval(this.autoRefreshProcId);
        }
        this.autoRefreshProcId = setInterval(this.reload.createDelegate(this), interval*1000);
	};
	tree.root.stopAutoRefresh = function(){
        if(this.autoRefreshProcId){
            clearInterval(this.autoRefreshProcId);
        }
    };
    tree.root.startAutoRefresh(60);*/
    
        
    tree.getSelectionModel().on('selectionchange', function(model, node) {
    	if (!node.chatWindow) {
    		node.chatWindow = new ChatWindow({user : CURRENT_USER, title : 'Chat with ' + node.id});
    	}
    	
    	node.chatWindow.show();
    });
    configs.layout = 'fit';
	configs.items = tree;
	
	ListUsersPanel.superclass.constructor.call(this, configs);
	//this.getListUsers();
	
};

Ext.extend(ListUsersPanel, Ext.Panel, {});

/*Ext.extend(ListUsersPanel, Ext.Panel, {
	getListUsers : function () {
		Ext.Ajax.request({
			url : 'listUsers.groovy',
			success : function (resp) {
				var result = eval(Ext.util.JSON.decode(resp.responseText));
				for (var i = 0; i < result.connectedUsers.length; i++) {
					this.add(new UserPanel({user : result.connectedUsers[i]}));
				}
				this.doLayout();
			},
			scope : this
		});
	}
});*/

ListUsersWindow = function(configs) {
	ListUsersWindow.superclass.constructor.call(this, {
		title : 'Connected users',
		width: 200,
	    height: 500,
	    minWidth: 100,
	    minHeight: 200,
	    layout: 'border',
	    plain: true,
	    bodyStyle: 'padding:5px;',
		x : Ext.getBody().getWidth() - 220,
		y : 100,

	    items : new ListUsersPanel({
	    	id : 'listUsers',
	    	region : 'center'
	    })
	});
};
Ext.extend(ListUsersWindow, Ext.Window, {});

function createConnectedUsersWindow() {
	var window = new ListUsersWindow();
	window.show();
}
Ext.onReady(createConnectedUsersWindow);
